package org.jeecg.modules.lock.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jeecg.modules.basic.entry.util.StringUtil;
import org.jeecg.modules.door.entity.LwgyJointDoor;
import org.jeecg.modules.lock.service.IOpenCloseElectricityService;
import org.jeecg.modules.lock.util.PasswordTempUtil;
import org.jeecg.modules.lock.entity.LwgyDoorLock;
import org.jeecg.modules.lock.mapper.LwgyDoorLockMapper;
import org.jeecg.modules.lock.service.LwgyDoorLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA
 *
 * @Description:
 * @Author : M-JGG
 * @create 2024/4/3 11:51
 */
@Slf4j
@Service
public class LwgyDoorLockServiceImpl extends ServiceImpl<LwgyDoorLockMapper, LwgyDoorLock> implements LwgyDoorLockService {

    @Autowired
    private LwgyDoorLockMapper lwgyDoorLockMapper;
    @Autowired
    private IOpenCloseElectricityService openCloseService;

    private static final String AUTH_URL = "https://server.hxjiot.com";// 鉴权接口 URL
    private static final String ACCOUNT_NAME = "15963111153";// 账户名
    private static final String PASSWORD = PasswordTempUtil.md5("990303");// 密码

    /**
     * 鉴权
     */
    @Override
    public String getAuthentication() {

        try {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

            // 构建请求体
            String requestBody = "{\"method\": \"apartmentLogin\", \"data\": {\"accountName\": \"" + ACCOUNT_NAME + "\", \"password\": \"" + PASSWORD + "\"}}";
            RequestBody body = RequestBody.create(mediaType, requestBody);
            // 构建请求
            Request request = new Request.Builder()
                    .url(AUTH_URL)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Content-Version", "1.0")
                    .build();

            // 发起请求
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonResponse = response.body().string();
                Map<String, Object> data = objectMapper.readValue(jsonResponse, new TypeReference<HashMap<String, Object>>() {
                });

                // 获取tokenId和expireTime
                Map<String, Object> responseData = (Map<String, Object>) data.get("data");
                String tokenId = (String) responseData.get("tokenId");
                return tokenId;
            } else {
                System.out.println("鉴权接口调用失败: " + response.message());
                return null;
            }
        } catch (Exception e) {
            System.out.println("调用鉴权接口报错: " + e.getMessage());
            return null;
        }
    }

    @Override
    public void insertThirdRoom(List<LwgyJointDoor> roomDataList) {
        lwgyDoorLockMapper.insertThirdRoom(roomDataList);
    }

    @Override
    public String handleDoorLock(LwgyDoorLock lwgyDoorLock) {
        String logType = lwgyDoorLock.getLogType();
        String logs = lwgyDoorLock.getLogAlert();
        List<LwgyJointDoor> doorList = lwgyDoorLockMapper.queryJointDoor();
        System.out.println("doorList ------ " + doorList);
        String lx = null;
        String strOpen = "门锁常开";
        String strClose = "关闭常开";
        if(logs.contains(strOpen)){
            switch (logType) {
                case "4":
                    lx = "1";
                    break;
                default:
                    break;
            }
        } else if (logs.contains(strClose)){
            switch (logType) {
                case "17":
                    lx = "2";
                    break;
                default:
                    break;
            }
        }
        if (lx != null) {
            String finalLx = lx;
            System.out.println("finalLx ------ " + finalLx);
            doorList.forEach(item -> {
                String xq = item.getThirdHouseName();
                String fjh = item.getRoomNumber();
                System.out.println("fjh ------ " + fjh);
                openCloseService.useSetSBKGData(xq, fjh, finalLx, "1");
            });
            return "Success";
        } else {
            return "Unsupported logType";
        }
    }

    @Override
    public void updateDoorLockState(String logId, String result) {
        LwgyDoorLock lwgyDoorLock = new LwgyDoorLock();
        lwgyDoorLock.setId(logId);
        lwgyDoorLock.setState(result);
        this.updateById(lwgyDoorLock);
    }
}
